import { intoRecurse } from '@u/common.js';
import { changeForm } from '@u/form.js';
import verify from './verify.js';
import getEnums from './enum.js';
import { getPermissionTree } from '@/api/home/system/permission.js';
import { isDynamicPermission } from '@/setting.js';

export default {
  data() {
    return {
      id: this.$route.params.id,
      showParentTree: false,
      parentString: '配置上级权限',
      chains: '',
      parentTmp: { // 临时存储上级权限
        id: 0,
        title: '',
        chains: '',
      },
      parentTree: [],
      formObj: {
        parentId: 0
      },
      opts: {
        title: {
          label: '权限名称：',
          value: '',
          required: true,
          position: [1, 1]
        },
        type: {
          label: '权限类别：',
          value: 3,
          required: true,
          position: [2, 1],
          type: 'radio',
          options: [],
          events: {
            change: this.changeType
          }
        },
        stateId: {
          label: '状态：',
          value: 1,
          position: [3, 1],
          type: 'switch',
          attrs: {
            activeValue: 1,
            inactiveValue: 2
          }
        },
        isShow: {
          value: true,
          label: '菜单栏显示：',
          position: [4, 1],
          type: 'switch',
          attrs: {
            disabled: false
          }
        },
        remark: {
          label: '备注：',
          value: '',
          position: [5, 1],
          attrs: {
            type: 'textarea'
          }
        },
        name: {
          label: '标识：',
          value: '',
          required: true,
          position: [1, 2],
          attrs: {
            placeholder: '请输入标识（只能输入字母、数字、下划线）',
          },
          directives: {
            input: /\w+/
          }
        },
        parent: {
          slot: true,
          label: '上级权限：',
          position: [2, 2]
        },
        sort: {
          label: '排序：',
          value: '',
          position: [3, 2],
          attrs: {
            placeholder: '请输入排序（只能输入非负整数）',
          },
          directives: {
            input: /0|[1-9]\d*/
          }
        },
        redirect: {
          label: '路径：',
          value: '',
          position: [4, 2],
          attrs: {
            placeholder: '请输入路径（只能输入字母、数字及常用符号）',
          },
          directives: {
            input: /[\w|:|/|?|&|%|.|=|#| ]+/
          }
        },
        icon: {
          label: '图标：',
          value: '',
          position: [5, 2],
          attrs: {
            placeholder: '请输入图标（只能输入字母、数字、下划线）',
          },
          directives: {
            input: /\w+/
          }
        }
      },
      cancelMessage: {
        msg: '确定取消吗？',
        title: '取消确认',
        options: {}
      },
      cancelNavTo: { path: '' },
      confirmNavTo: { path: '' }
    };
  },
  async created() {
    if (this.id) {
      await this.detailFn(this.id).then(res => {
        if (res.code == 200) {
          this.parentTmp = res.data.parent;
          this.parentString = res.data.parent.title || '配置上级权限';
          this.formObj.parentId = res.data.parent.id;
          res.data.type = res.data.type.id;
          res.data.stateId = res.data.state.id;
          if (res.data.type == 4 || res.data.type == 5) {
            this.opts.isShow.attrs.disabled = true;
          }
          changeForm(this.opts, res.data, true);
        }
      });
    }
    getPermissionTree().then(res => {
      if (res.code == 200) {
        let index = -1;
        intoRecurse(res.data, (item, options) => {
          if (item.level == 1) {
            if (item.id == this.id) {
              index = options.index;
            }
          }
          if (this.id && item.id == this.formObj.parentId) {
            const i = item.children.findIndex(c => c.id == this.id);
            item.children.splice(i, 1);
            this.chains = item.chains;
            item.isChecked = true;
          }
        }, { chainName: 'id' });
        if (this.id) {
          if (index != -1) {
            res.data.splice(index, 1);
          }
          intoRecurse(res.data, (item, options) => {
            const arr = this.chains.split(','),
              i = arr.findIndex(a => a == item.id);
            if (i != -1) {
              item.isExpand = true;
            }
            if (i == arr.length - 1) {
              item.isExpand = false;
              options.close = true;
            }
          });
        }
        this.parentTree = res.data;
      }
    });
    getEnums(this);
  },
  activated() {
    this.$store.commit('layout/initManuallyRefresh', async() => {
      getEnums(this);
    });
  },
  methods: {
    changeType(e) {
      const isShow = this.opts.isShow;
      if (e == 4 || e == 5) {
        isShow.value = false;
        this.$set(isShow.attrs, 'disabled', true);
      } else {
        this.$set(isShow.attrs, 'disabled', false);
      }
    },
    chooseParent(row, all) { // 递归  只可以选择一个勾选
      intoRecurse(all, item => {
        if (item.id != row.id) {
          this.$set(item, 'isChecked', false);
        } else {
          this.parentTmp.id = item.isChecked ? row.id : 0;
          this.parentTmp.title = item.isChecked ? row.title : '配置上级权限';
          this.parentTmp.chains = item.isChecked ? row.chains : '';
        }
      });
    },
    confirmParent() {
      this.formObj.parentId = this.parentTmp.id || 0;
      this.parentString = this.parentTmp.title || '配置上级权限';
      this.chains = this.parentTmp.chains;
      this.showParentTree = false;
    },
    cancelParent() {
      intoRecurse(this.parentTree, item => {
        if (this.formObj.parentId == item.id) {
          item.isChecked = true;
        } else {
          item.isChecked = false;
        }
      });
      this.showParentTree = false;
    },
    async confirm() {
      const params = changeForm(this.opts, this.formObj);
      if (verify(this, params)) {
        params.sort = params.sort || 0;
        let res = {};
        if (!this.id) {
          res = await this.addFn({ data: params });
          this.confirmNavTo.params.id = res.data.id;
        } else {
          res = await this.editFn(this.id, { data: params });
        }
        if (res.code == 200) {
          if (isDynamicPermission) {
            this.permissonChangeFn(this);
          }
          this.confirmNavTo.params.pages = { Permission: this.chains };
          this.$router.push(this.confirmNavTo);
        }
      }
    },
    cancel() {
      this.$confirm(this.cancelMessage.msg, this.cancelMessage.title, {
        type: 'warning',
        ...this.cancelMessage.options
      }).then(() => {
        this.navigateBack(this.cancelNavTo);
      });
    }
  },
  components: {
    Form: () => import('@c/Form.vue'),
    CheckTree: () => import('@c/CheckTree')
  }
};
